<?php
/*
	处理分类

*/

class User extends Main{
	  //取得用户信息
	  public function userInfo($user_id){
		$user_id = !empty($user_id) ? intval($user_id) : @$_SESION['user_id'];
		$user_id = $user_id ? $user_id :0;
		$sql = "select u.*,t.name as type from users as u inner join typeids as t on t.type_id=u.type_id  where u.user_id=$user_id  ";

		$data = $GLOBALS['db']->getRow($sql);

		$data['info'] = @$this->json2Array($data['info']);
		//print_r($data);die();

		return $data;
	  }
	  //取得用户信息
	  public function userInfo2($email,$field='email'){

		$sql = "select * from users where $field='".$email."'";
		$data = $GLOBALS['db']->getRow($sql);
		$type_id = $data['type_id'];
		$data['type'] = $GLOBALS['db']->getOne("select name from typeids where type_id=$type_id");

		return $data;
	  }

	  //编辑收货地址
	  public function updateAddr($json){
		 $json = $this->addrFormat($json);
		 $data = $this->json2Array($json);
		 $sql = "update user_address set address ='".mysql_real_escape_string($json)."' where address_id='".$data['address_id']."'";
		 mysql_query($sql);
		 $res['address'] = $data ;
		 $res['addr_str'] = $this->addrStr($data);
		 return $res;

	  }

	  //增加收货地址
	  public function addAddr($json,$sess=true){

		$json = $this->addrFormat($json);
		if($_SESSION['user_id'] && $sess)
		{
			$user_id = $_SESSION['user_id'];
			$sql = "insert into user_address(`address`,`user_id`) values('".mysql_real_escape_string($json)."','".$user_id."')";
			mysql_query($sql);
		}

		$address = $this->json2Array($json);
		$res['address'] = $this->json2Array($json);
		$res['addr_str'] = $this->addrStr($address);

		if($this->checkAddr($res))
		{
			$json_data = base64_encode(json_encode($res));
			setCookie('ETH_SESS',USER_AGENT,strtotime("+1 years"),'/ ');
			setCookie('ETH_ADDR',$json_data,strtotime("+1 years"),'/ ');
			$_SESSION[USER_AGENT]['address'] = json_encode($res);
			return $res;
		}
		else
		{
			return false;
		}

	  }

	  //获取格式化收货人信息
	  public function addrFormat($data){

			$data = $this->json2Array($data);
			if(!is_array($data)) return '';

			$data['province_str'] = !empty($data['province']) ? $this->getRegionOne($data['province']) : $data['province_t'] ;
			$data['country_str'] = $this->getRegionOne($data['country']);
			return json_encode($data);

	  }

	  //检查收货地址
	  public function checkAddr($data){

		  $res = true;

		  $addr = @$data['address'];

		  if(empty($addr['user_name']))
		  {

			$res = false;
		  }
		  if(empty($addr['email']))
		  {
			$res = false;
		  }
		  if(empty($addr['tel']))
		  {
			$res = false;
		  }
		  if(empty($addr['address']))
		  {
			$res = false;
		  }
		  if(empty($addr['city']))
		  {
			$res = false;
		  }
		  if(empty($addr['zipcode']))
		  {
			$res = false;
		  }
		  if(empty($addr['province_str']))
		  {
			$res = false;
		  }
		  if(empty($addr['country_str']))
		  {
			$res = false;
		  }

		  return $res;

	  }


	  //取得收货人str
	  public function addrStr($data){
		if(!$data) return '';

		$str = sprintf("%s (%s %s , %s %s %s) %s %s",$data['user_name'],$data['address'],$data['city'],
			$data['province_str'],$data['zipcode'],$data['country_str'],$data['tel'],$data['email']);

		return $str;
	  }


	  //取得一条地址信息
	  public function getAddr($address_id=0){

		if($address_id)
		{
			$sql = "select address_id,address from user_address where address_id=$address_id order by address_id desc";

			$data = $GLOBALS['db']->getRow($sql);

			if($data)
			{
				$address = $this->json2Array($data['address']);
				$s_addr = @$this->json2Array($_SESSION[USER_AGENT]['address']);

				$data['addr_str'] = $this->addrStr($address);

				$data['address'] = $address;
				if(@$s_addr['address_id'] == $address_id)
				{
					$data['checked'] = 1;
				}
			}

		}
		else
		{

			$data = !empty($_SESSION[USER_AGENT]['address']) ? $_SESSION[USER_AGENT]['address'] : $this->cookieAddr();

			$data = $this->json2Array($data);
		}

		if($this->checkAddr($data))
		{
			return $data;
		}


		return false;
	  }
	 //取得用户地址信息
	  public function getAddrList($user_id){
		if($user_id)
		 {
			$sql = "select address_id  from user_address where user_id=$user_id order by address_id desc";
			$data = $GLOBALS['db']->getAll($sql);

			foreach($data as $key=>$val)
			{
				$address_id = $val['address_id'];
				$val['addr'] = $this->getAddr($address_id);
				$data[$key] = $val;
			}
		}
		else
		{
			$addr = $this->getAddr();
			$data[0]['address'] = $addr['address'];
			$data[0]['addr_str'] = $addr['addr_str'];;
		}

		return $data;
	  }
	  //删除收货人信息
	   public function delAddr($address_id){
			if($address_id)
		   {
				$sql = "delete from user_address where address_id=$address_id";
				return mysql_query($sql);
		   }
		   else
		   {
				unset($_SESSION[USER_AGENT]['address']);
				setCookie('ETH_ADDR',"",time()-3600,'/ ');
		   }
	  }
	  //增加用户
	  public function addUser($email,$passwd=''){
		 if(empty($email)) return false;
		$res = false;
		if(!$this->isRegister($email))
		 {
			$sql = "insert into users(`email`,`passwd`) values('".$email."','".$passwd."')";
			$res = mysql_query($sql);
			$user_id = mysql_insert_id();
			$s = $this->userInfo($user_id);
			$this->userSession($s);
		 }

		return $res;
	  }
	  //创建user session
	  public  function userSession($user_info){
		$_SESSION['user_info'] = $user_info;
		$_SESSION['email'] = $user_info['email'];
		$_SESSION['user_id'] = $user_info['user_id'];
	  }
	  //用户登录
	  public function userLogin($data){
		$email = $data['email'];
		$passwd = $data['passwd'];
		$field = !empty($data['field']) ? $data['field'] : 'email';
		$res = false;

		if($this->isRegister($email,$field))
		{
			$sql = "select passwd from users where $field='".$email."'";

			$pass = $GLOBALS['db']->getOne($sql);
			if(md5($passwd) == $pass)
			{
				$s = $this->userInfo2($email,$field);

				mysql_query ("update users set last_login=".time()." where user_id=".$s['user_id']);
				if($s['status']==-1)
					return -1;
				$this->userSession($s);
				@$_SESSION['user_info']['pa'] = $passwd;
				$res = true;

			}
		}
		return $res;
	  }

	  //自定登录
	  public function autoLogin($data){
		$res = false;
		if($this->isRegister($data['email']))
		{
			$s = $this->userInfo2($data['email']);
			$this->userSession($s);
			$_SESSION['fb_user'] = true;
		}
		else
		{
			if($this->addUser($data['email']))
			{
				$res = true;
			}
		}
		echo $res;
		die();
		return $res;
	  }
	 //检查是否已经注册
	 public function isRegister($email,$field='email'){
	    if(empty($email)) return false;
		$sql = "select * from users where $field='".$email."'";
		$res = $GLOBALS['db']->getRow($sql);
		if($res)
			$res['info'] = @$this->json2Array($res['info']);

		return $res;
	 }
	 //设置头像
	 public function userEdit($data){
		$user_info = $this->userInfo($_SESSION['user_id']);
		$email  = isset($data['email']) ? $data['email'] : $user_info['email'];
		$passwd = isset($data['passwd']) ? md5($data['passwd']) : $user_info['passwd'];
		$sex = isset($data['sex']) ? $data['sex'] : $user_info['sex'];
		$birthday = isset($data['birthday']) ? $data['birthday'] : $user_info['birthday'];
		$avater = isset($data['avater']) ? $data['avater'] : $user_info['avater'];

		$sql = "update users set avater='".$avater."',birthday='".$birthday."',sex='".$sex."',passwd='".$passwd."',email='".$email."' where user_id='".$_SESSION['user_id']."'";

		return mysql_query($sql);
	 }
	 //用户注销
	 public function logOut(){

		unset($_SESSION['user_info']);
		unset($_SESSION['user']);
		unset($_SESSION['email']);
		unset($_SESSION['user_id']);
		unset($_SESSION['fb_user']);
		return true;
	 }
	 //更新用户信息
	 public function userPasswdReset($email,$passwd){
		$sql = "update users set passwd='".$passwd."' where email='".$email."';";
		return mysql_query($sql);
	 }

	 //生成临时密码
	 public function tempPasswd(){
		return substr(md5(substr(USER_AGENT.time(),10,10)),10,10);
	 }

	 //取得评论 $type_id 对同行的评论 沉底
	public function reviewList($start,$size,$where='',$user_info=false,$reply=false,$type_id=0){
		$sql = "select * from review $where limit $start,$size";

		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$r_id = $val['r_id'];
			$time = $val['add_time'];
			$val['add_time'] = $this->dateFormat($val['add_time'],'m-d H:i:s');
			if($user_info)
			{
				$val['user_info'] = $GLOBALS['User']->userInfo($val['user_id']);
				$r['type_id'] = @$val['user_info']['type_id'];
				if($r['type_id']==$type_id && $time>(time()-365*24*3600))
				{
					$r['add_time'] = $time-10*365*24*3600;
					//echo $type_id."<br>";
				}

				$GLOBALS['db']->autoExecute('review',$r,'update',"r_id=$r_id");
			}
			if($reply)
				$val['reply'] = $this->reviewList(0,10,"where rp_id=$r_id",$user_info);
			$data[$key] = $val;
		}

		return $data;
	}

	//用户列表
	public function userList($start,$size,$where=''){
		$sql = "select * from users $where limit $start,$size";
		$data = $GLOBALS['db']->getAll($sql);
		return $data;
	}

	//is admin
	public function isAdmin($admin){
		if(!empty($admin['user_name']) && !empty($admin['passwd']))
		{
			$sql = "select * from admin_user where user_name='".$admin['user_name']."' and password='".md5($admin['passwd'])."'";
			$row = $GLOBALS['db']->getRow($sql);

			if($row)
			{
				return true;
			}
		}
		return false;
	}
	//goods get admin
	public function goodsAdmin($goods_id=0){
		$user = $GLOBALS['db']->getRow("select u.* from  users as u inner join goods as g on g.cat_id=u.cat_id where u.mag=1 and g.goods_id=$goods_id ");
		$user['info'] = @$this->json2Array($user['info']);

		return $user;
	}
	//回复，评论的邮件提醒
	public function sendMailNotice($data){
		if(!empty($data['rp_id']))
			$type='reply';
		else
			$type = 'review';
		$tmp = $this->mailTemplateOne('action');
		$mail['subject'] = $tmp['subject'];
		if($type=='review')
		{

			$url = '<a href="http://dq.cmbc.com.cn/xiaoqu/goods.php?id=' . $data['id'] . '">点击查看详情</a>';
			$user = $this->goodsAdmin($data['id']);
			$mail['to'] = array (
				$user['email']//'81434146@qq.com'
			);
			$com = array (
				"您有新的订单评论<br/>内容：" . $data['content']
			 . "<br/>"
			 . $url . "<br/>" .
			"请及时处理!<br/>" .
			"From : ".$GLOBALS['_CFG']['shop_name']."<br/>".
			"Date : " . $this->dateFormat(time()),
			);

		}
		elseif($type=='reply')
		{
			$url = '<a href="http://dq.cmbc.com.cn/xiaoqu/goods.php?id=' . $data['id'] . '">点击查看详情</a>';
			$review = $GLOBALS['db']->getRow("select * from review where r_id=".$data['rp_id'].";");
			$user = $this->userInfo($review['user_id']);
			$mail['to'] = array (
				$user['email']
			);
			$com = array (
				"您有新的回复<br/>内容：" . $data['content']
			 . "<br/>"
			 . $url . "<br/>" .
			"请及时处理!<br/>" .
			"From : ".$GLOBALS['_CFG']['shop_name']."<br/>".
			"Date : " . $this->dateFormat(time()),
			);
		}
		$mail['body'] = sprintf($tmp['content'], $com[0]);

		$this->sendMail($mail);
	}
	//积分发送
	public function sendGold($data){
		$res = false;

		$data['add_time'] = time();
		//初始化信息
		$buyer_type =  '-';
		$geter_type =  '+';
		$buyer_id = preg_replace("/\w_/","",$data['buyer']);
		$geter_id = preg_replace("/\w_/","",$data['geter']);

		switch($data['type'])
		{
			case '1': //购买商品 ,支出者--user，收入者--category
				$type=1;
				$buyer_table = 'users';
				$buyer_field = 'user_id';
				$geter_table = 'category';
				$geter_field = 'cat_id';
				break;
			case '2'://店铺划分，支出者--category,收入者--user
				$type=2;
				$buyer_table = 'category';
				$buyer_field = 'cat_id';
				$geter_table = 'users';
				$geter_field = 'user_id';
				break;
			case '3':
				$type=3;
				$geter_table = 'users';
				$geter_field = 'user_id';
				break;
			case '4': //购买商品 ,支出者--user，收入者--category
				$type=4;
				$buyer_table = 'users';
				$buyer_field = 'user_id';
				$geter_table = 'category';
				$geter_field = 'cat_id';
				break;

		}

		//判断支出者余额是否足够
		$overange = $GLOBALS['db']->getOne("select gold from $buyer_table where $buyer_field=".$buyer_id."");
		if($overange<$data['amount'])

			return false;

		//支出者 扣掉积分

		$value = 'gold'.$buyer_type.$data['amount'];
		$sql = "update $buyer_table set gold=$value where $buyer_field=".$buyer_id."";

		//收入者得到积分
		$value1 = 'gold'.$geter_type.$data['amount'];

		$sql2 = "update $geter_table set gold=$value1 where $geter_field=".$geter_id;

		if(mysql_query($sql) && mysql_query($sql2) && $GLOBALS['db']->autoExecute('gold_log',$data))
		{
			$res = true;

		}
		return $res;
	}

	//积分记录
	public function goldLog($start,$size,$where){
		$sql = "select * from gold_log $where limit $start,$size";

		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$val['add_time'] = $this->dateFormat($val['add_time']);
			$data[$key] =$val;
		}
		return $data;
	}
	//积分记录明细
	public function goldLogDetail($log_id){
		$sql = "select * from gold_log where log_id=$log_id";

		$data = $GLOBALS['db']->getRow($sql);
		$buyer_id = preg_replace("/u_/","",$data['buyer']);
		$data['buyer_info'] = $this->userInfo($buyer_id);

		return $data;
	}

	//是否是店铺管理员
	public function isCatAdmin($cat_id){

		$is_admin = @($_SESSION['user_info']['cat_id']== $cat_id && $_SESSION['user_info']['mag']) || 0;
		return $is_admin;
	}
	//是否是店铺人员
	public function inCat($cat_id){

		$in_cat = @($_SESSION['user_info']['cat_id']== $cat_id) || 0;
		return $in_cat;
	}


	//购买商品后评价积分
	public function orderGold($goods_id,$order_id,$score,$review_id){

		//更新订单评论
		$sql = "update order_info set review_id=$review_id where order_id=$order_id";
		mysql_query($sql);

		$gold  = $GLOBALS['gold']['gold'];


		$user_info = $_SESSION['user_info'];


		$order_amount = (int)$GLOBALS['db']->getOne("select order_amount from order_info where order_id=$order_id");

		$user_return = $gold['order_review']['return'] * $order_amount;

		//评论后增加用户积分
		$user_gold['comment'] = '订单评论成功，系统返回'.($user_return).' 青币 给 '.$user_info['user_name'].' 操作人:system';
		$user_gold['return'] = $user_return;
		$user_gold['user_id'] = $user_info['user_id'];
		$this->goldLogReturnUser($user_gold);


		//评论后给商家加减分
		$cat_id = $GLOBALS['db']->getOne("select cat_id from goods where goods_id=$goods_id");;

		$cat = $GLOBALS['Cate']->catInfo($cat_id);
		$cat_return = $gold['order_review'][$score] * $order_amount;
		if($score==3)
		{
			$msg='推广成功,系统返回';
		}
		elseif($score==2)
		{
			$msg='暂无效果,系统返回';
		}
		elseif($score==1)
		{
			$msg='推广失败，系统扣除';

		}
		$cat_gold['comment'] = $user_info['user_name']." 订单评论:$msg ".($cat_return).' 青币 给 '.$cat['cat_name'].' 操作人:system';
		$cat_gold['return'] = $cat_return;
		$cat_gold['cat_id'] = $cat_id;
		$this->goldLogReturnCat($cat_gold);




	}
	//系统返回积分
	public function goldLogReturnCat($gold){
		$cat_gold['comment'] = $gold['comment'] ? $gold['comment'] :'系统返回'.$gold['return'].' 青币 操作人:system';
		$cat_gold['geter'] = 'c_'.$gold['cat_id'];
		$cat_gold['buyer'] = !empty($gold['buyer']) ? $gold['buyer'] : 'system';
		$cat_gold['type'] = 3;
		$cat_gold['amount'] = $gold['return'];
		$cat_gold['add_time'] = time();

		$GLOBALS['db']->autoExecute('gold_log',$cat_gold);

		return mysql_query("update category set gold=gold+".($gold['return'])." where cat_id=".$gold['cat_id']."");
	}
	public function goldLogReturnUser($gold){
		$cat_gold['comment'] = $gold['comment'] ? $gold['comment'] :'系统返回'.$gold['return'].' 青币 操作人:system';
		$cat_gold['geter'] = 'u_'.$gold['user_id'];
		$cat_gold['buyer'] =  !empty($gold['buyer']) ? $gold['buyer'] : 'system';
		$cat_gold['type'] = 3;
		$cat_gold['amount'] = $gold['return'];
		$cat_gold['add_time'] = time();

		$GLOBALS['db']->autoExecute('gold_log',$cat_gold);

		mysql_query("update users set gold=gold+".($gold['return'])." where user_id=".$gold['user_id']."");
	}

	//是否签到
	public function isQiandao(){
		$user_id = @$_SESSION['user_id'];

		if(!empty($_SESSION['qiandao']) || !empty($_COOKIE['user'][$user_id]['qiandao']))
		{
			return true;
		}
		return false;
	}

	//wishlist
	public function wishlist($start=0,$size=10,$where="",$goods=true){
		$sql = "select * from wishlist $where  order by add_time desc limit $start,$size ;";
		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			if($val['type']==1)
			{
				$val['goods'] = $GLOBALS['Goods']->goodsInfo($val['id']);
			}
			else if($val['type']==2)
			{
				$cat_id = $val['id'];
				$cat = $GLOBALS['Cate']->categoryAll(0,1,"where cat_id=$cat_id");
				$val['cat'] = @$cat[0];
			}

			$val['add_time'] = $this->dateFormat($val['add_time']);
			$data[$key] = $val;
		}

		return $data;

	}


	//是否收藏
	public function iSwished($id,$type=1){
		$user_id = @$_SESSION['user_id'];
		$sql = "select * from wishlist where id=$id and type=$type and user_id=$user_id";
		return $GLOBALS['db']->getRow($sql);
	}




}

?>
